package group.anglers.om.core.persistence.impls;

import group.anglers.om.core.exceptions.OmException;
import group.anglers.om.core.exceptions.UnExpectedException;
import group.anglers.om.core.persistence.serialization.impl.LocalModelSerializationArchived;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
 * 
 * @author an.pham
 *
 */
public class JTAPersistence extends PersistenceImpl {
	private Connection connection;
	private String jndi;
	
	public JTAPersistence(String jndi) throws OmException {
		super(LocalModelSerializationArchived.getInstance());
		
		this.jndi = jndi;
		
		connect();
	}

	@Override
	protected Connection getConnection() throws OmException {
		try {
			if(connection != null && connection.isClosed()){
				connect();
			}
		} catch (SQLException e) {
			throw new UnExpectedException(e);
		}
		return connection;
	}

	private void connect() throws OmException {
		try {
			InitialContext initialContext = new InitialContext();
			DataSource datasource = (DataSource) initialContext.lookup(jndi);
			
			connection = datasource.getConnection();
		} catch (Exception e) {
			throw new UnExpectedException(e);
		}
	}
}
